package com.cos66.handler;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

import com.cos66.model.MagazineDetailItem;

public class MagazineDetailHandler extends DefaultHandler {

	private MagazineDetailItem item;
	private List<MagazineDetailItem> data;
	private StringBuilder sb = new StringBuilder();

	private static final String TAG = "MagazineDetailHandler";

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		data = new ArrayList<MagazineDetailItem>();
		Log.d(TAG, "startDocument");
		super.startDocument();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		Log.d(TAG, "startElement");
		sb.setLength(0);
		if (localName.equals("item")) {
			item = new MagazineDetailItem();
			Log.d(TAG, "New MagazineDetailItem");
		}
		super.startElement(uri, localName, qName, attributes);
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		super.characters(ch, start, length);
		String str = new String(ch, start, length);
		Log.d(TAG, "String==>" + str);
		sb.append(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		String str = sb.toString();
		Log.d(TAG, localName + "===>" + str);
		if (localName.equals("detailId")) {
			item.setDetailId(Long.parseLong(str));
		} else if (localName.equals("detailType")) {
			item.setDetailType(Integer.parseInt(str));
		} else if (localName.equals("detailTitle")) {
			item.setDetailTitle(str);
		} else if (localName.equals("detailBrief")) {
			item.setDetailBrief(str);
		} else if (localName.equals("detailImageUrl")) {
			item.setDetailImageUrl(str);
		} else if (localName.equals("detailResourceUrl")) {
			item.setDetailResourceUrl(str);
		}
		if (localName.equals("item")) {
			Log.d(TAG, "Data Add MagazineDetailItem");
			data.add(item);
		}
		Log.d(TAG, "endElement");
		super.endElement(uri, localName, qName);
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		Log.d(TAG, "endDocument");
		super.endDocument();
	}

	public List<MagazineDetailItem> getData() {
		return data;
	}
	
}
